import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';

import '../../model/model.dart';
import '../../notify/globalState.dart';
import '../../tool/assets.dart';
import 'pass_type.dart';

class PassView extends StatefulWidget {
  Passmodel pass;
  void Function(Passmodel, String) onSendBlock;
  PassView({super.key, required this.pass, required this.onSendBlock});

  @override
  State<PassView> createState() => _PassViewState();
}

class _PassViewState extends State<PassView> {
  final _textEditingController = TextEditingController();
  List<bool> _isHighlight = [false, false];
  bool get enable {
    return widget.pass.enable && widget.pass.select && widget.pass.isBypass == false;
  }

  @override
  void initState() {
    super.initState();
    _textEditingController.text = '${widget.pass.freq}';
    _textEditingController.addListener(() {
      String text = _textEditingController.text;
      // 自动添加前导0
      if (text.isNotEmpty && text[0] == '.') {
        _textEditingController.text = '0$text';
        return;
      } else if (text.length > 1 && text[0] == '0' && text[1] != '.') {
        _textEditingController.text = text.substring(1, text.length);
        return;
      }
    });
  }

  @override
  void dispose() {
    _textEditingController.dispose();
    super.dispose();
  }

  ///处理频率范围
  void _handleFreq(int freq) {
    widget.pass.freq = max(freq, widget.pass.min_freq);
    widget.pass.freq = min(widget.pass.freq, widget.pass.max_freq);
    setState(() {});
    widget.onSendBlock(widget.pass, 'freq');
  }

  ///分段选择
  Widget get_toggle() {
    List<bool> select_list = widget.pass.type!.slopeList.map(($0) => widget.pass.type!.slope == $0).toList();
    return ToggleButtons(
      constraints: const BoxConstraints(maxWidth: 40, minWidth: 40),
      isSelected: select_list,
      onPressed: !enable
          ? null
          : (int index) {
              setState(() {
                widget.pass.type?.slope = widget.pass.type!.slopeList[index];
              });

              ///slope
              widget.onSendBlock(widget.pass, 'slope');
            },
      borderRadius: BorderRadius.circular(0), // 取消边框圆角
      borderColor: Colors.transparent, // 取消边框颜色
      selectedColor: enable ? Color_select_btn : Color_disEnable,
      selectedBorderColor: Colors.transparent, // 取消选中状态的边框
      fillColor: Colors.transparent,
      splashColor: Colors.white10.withOpacity(0.1),
      children: widget.pass.type!.slopeList.map(($0) {
        return Padding(
          padding: EdgeInsets.symmetric(horizontal: 4.0 * GlobalConfig.scaleH),
          child: Text(
            '${$0}',
            style: TextStyle(
                color: !enable
                    ? Color_disEnable
                    : $0 == widget.pass.type!.slope
                        ? Color_select_btn
                        : Colors.black),
          ),
        );
      }).toList(),
    );
  }

  ///左右增减按钮
  Widget get_btn(int index) {
    return GestureDetector(
        onTapDown: !enable ? null : (details) => setState(() => _isHighlight[index] = true),
        onTapUp: !enable ? null : (details) => setState(() => _isHighlight[index] = false),
        onTap: !enable ? null : () => _handleFreq(index == 0 ? widget.pass.freq - 1 : widget.pass.freq + 1),
        onTapCancel: !enable ? null : () => setState(() => _isHighlight[index] = false),
        child: Image.asset(
          index == 0 ? assets.left_btn : assets.right_btn,
          width: 30 * GlobalConfig.scaleH,
          height: 30 * GlobalConfig.scaleH,
          color: _isHighlight[index] == true
              ? Colors.black.withOpacity(0.4)
              : enable
                  ? Colors.black
                  : Color_disEnable,
        ));
  }

  ///输入框
  Widget get_input(int num) {
    _textEditingController.text = '${num}';
    return TextField(
      enabled: enable,
      textAlignVertical: TextAlignVertical.center,
      textAlign: TextAlign.center,
      cursorHeight: 20, // 设置光标高度
      cursorWidth: 0.5,
      cursorColor: Color_border, //设置光标颜色
      style: TextStyle(fontSize: 14, color: enable ? Colors.black : Color_disEnable),
      controller: _textEditingController,
      keyboardType: const TextInputType.numberWithOptions(decimal: true),

      ///输入规则限制
      inputFormatters: [
        LengthLimitingTextInputFormatter(5), // 限制输入最大长度为3
        //FilteringTextInputFormatter.digitsOnly, // 只允许输入数字
        FilteringTextInputFormatter(
          RegExp(r'^\d+$'), // 允许纯数字
          allow: true,
        ),
      ],

      ///响应方法
      // onTap: widget.beginEdit,
      onChanged: (value) {
        int freq = value.float.toInt();
        if (freq < widget.pass.min_freq) {
          return;
        }
        _handleFreq(value.float.toInt());
      },
      onSubmitted: (value) => _handleFreq(value.float.toInt()),
      // onEditingComplete: () =>
      //     widget.onSubmit!(_textEditingController.text.float),

      ///边框设置
      decoration: InputDecoration(
        focusColor: Color_select_btn,
        // isDense: true, // 密集模式，减少内部空间
        contentPadding: EdgeInsets.symmetric(vertical: 12 * GlobalConfig.scaleH), // 调整垂直内边距以使文本居中
        border: InputBorder.none, // 设置无边框
        enabledBorder: InputBorder.none, // 输入框启用时无边框
        focusedBorder: InputBorder.none, // 输入框获得焦点时无边框
      ),
    );
  }

  ///第二第三行布局
  Widget _secondLayout(double width, String left, String right, Widget middle) {
    Widget titleItem(String text, bool isLeft) {
      return Positioned(
        left: isLeft ? 15 : width - 75,
        right: isLeft ? width - 90 : 15,
        top: 10 * GlobalConfig.scaleH,
        height: 30 * GlobalConfig.scaleH,
        child: Container(
          alignment: Alignment.centerLeft,
          child: Text(text, style: TextStyle(color: enable ? Colors.black : Color_disEnable, fontSize: 14)),
        ),
      );
    }

    return SizedBox(
      height: 40 * GlobalConfig.scaleH,
      width: width,
      child: Stack(
        children: [
          titleItem(left, true),
          Positioned(
              left: 95,
              right: 95,
              top: 10 * GlobalConfig.scaleH,
              height: 30 * GlobalConfig.scaleH,
              child: Center(child: middle)),
          titleItem(right, false),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    globalState.state = NotifyData(key: '隐藏下拉框');
    int freq = widget.pass.ishigh && widget.pass.isBypass
        ? widget.pass.min_freq
        : widget.pass.ishigh == false && widget.pass.isBypass
            ? widget.pass.max_freq
            : widget.pass.freq;
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).unfocus();
      },
      child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constrains) {
        return Column(
          children: [
            ///顶部按钮
            PassTypeView(pass: widget.pass, onClick: widget.onSendBlock),

            ///slope  一行
            _secondLayout(
              constrains.maxWidth,
              'Slope',
              'dB/Oct',
              get_toggle(),
            ),

            ///frequency一行
            _secondLayout(
              constrains.maxWidth,
              'Frequency',
              'HZ',
              Container(
                height: 30 * GlobalConfig.scaleH,
                // decoration: BoxDecoration(
                //   border: Border.all(color: Colors.black, width: 0.5),
                //   borderRadius: BorderRadius.circular(4),
                // ),
                child: Stack(
                  children: [
                    Positioned(left: 0, top: 0, height: 30 * GlobalConfig.scaleH, child: get_btn(0)),
                    Positioned(
                        left: 10,
                        right: 10,
                        top: 0.7 * GlobalConfig.scaleH,
                        height: 0.5 * GlobalConfig.scaleH,
                        child: Container(color: enable ? Colors.black : Color_disEnable)),
                    Positioned(left: 30, right: 30, top: 0, height: 30 * GlobalConfig.scaleH, child: get_input(freq)),
                    Positioned(
                        left: 10,
                        right: 10,
                        bottom: 0.85 * GlobalConfig.scaleH,
                        height: 0.5 * GlobalConfig.scaleH,
                        child: Container(color: enable ? Colors.black : Color_disEnable)),
                    Positioned(right: 0, top: 0, height: 30 * GlobalConfig.scaleH, child: get_btn(1)),
                  ],
                ),
              ),
            ),
            SizedBox(height: 10 * GlobalConfig.scaleH),
            Container(
              padding: const EdgeInsets.only(left: 40, right: 40),
              alignment: Alignment.bottomCenter,
              height: 40 * GlobalConfig.scaleH,
              child: kSlider(
                value: freq.toDouble(),
                min: widget.pass.min_freq.toDouble(),
                max: widget.pass.max_freq.toDouble(),
                activeColor: Color_theme,
                thumbColor: Color_theme,
                enable: enable,
                onChanged: (p0) {
                  setState(() {
                    widget.pass.freq = ((p0 * 100) / 100).toInt();
                  });
                },
                onChangedForSend: (p0) {
                  widget.onSendBlock(widget.pass, 'freq');
                },
              ),
            ),
          ],
        );
      }),
    );
  }
}
